Grokking Tree Coding Patterns for Interviews
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Course Overview
Basics of Tree
Introduction to Tree
Types of Tree
BST Traversal Techniques
BST Operations
Level Order Traversal Pattern (easy)
Introduction to Level Order Traversal Pattern
Reverse Level Order Traversal (easy)
Solution: Reverse Level Order Traversal
Find Largest Value in Each Tree Row (medium)
Solution: Find Largest Value in Each Tree Row
Maximum Width of Binary Tree (medium)
Solution: Maximum Width of Binary Tree
Maximum Level Sum of a Binary Tree (medium)
Solution: Maximum Level Sum of a Binary Tree
Zigzag Traversal (medium)
Solution: Zigzag Traversal
Even Odd Tree (medium)
Solution: Even Odd Tree
N-ary Tree Level Order Traversal (hard)
Solution: N-ary Tree Level Order Traversal
Introduction to Tree Depth Pattern
Maximum Depth (or Height) of Binary Tree (easy)
Solution: Maximum Depth (or Height) of Binary Tree
Minimum Depth of a Binary Tree (easy)
Solution: Minimum Depth of a Binary Tree
Balanced Binary Tree (easy)
Solution: Balanced Binary Tree
Tree Diameter (easy)
Solution: Tree Diameter
Maximum Depth of N-ary Tree (easy)
Solution: Maximum Depth of N-ary Tree
Find maximum depth of subtree (medium)
Solution: Find maximum depth of subtree
Introduction to Root to Leaf Path Pattern
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Sum of Root To Leaf Binary Numbers (easy)
Solution: Sum of Root To Leaf Binary Numbers
Insufficient Nodes in Root to Leaf Paths (medium)
Solution: Insufficient Nodes in Root to Leaf Paths
Smallest String Starting From Leaf (medium)
Solution: Smallest String Starting From Leaf
Pseudo-Palindromic Paths in a Binary Tree (medium)
Solution: Pseudo-Palindromic Paths in a Binary Tree
All Paths for a Sum (medium)
Solution: All Paths for a Sum
Sum of Path Numbers (medium)
Solution: Sum of Path Numbers
Path With Given Sequence (medium)
Solution: Path With Given Sequence
Count Paths for a Sum (medium)
Solution: Count Paths for a Sum
Introduction to Leaf Processing Pattern
Sum of Left Leaves (easy)
Solution: Sum of Left Leaves
Leaf-Similar Trees (easy)
Solution: Leaf-Similar Trees
Check if all leaves are at same level (medium)
Solution: Check if all leaves are at same level
Delete Leaves With a Given Value (medium)
Solution: Delete Leaves With a Given Value
Deepest Leaves Sum (medium)
Solution: Deepest Leaves Sum
Introduction to Tree View Pattern
Right View of a Binary Tree (medium)
Solution: Right View of a Binary Tree
Top View Of the Binary Tree (medium)
Solution: Top View Of the Binary Tree
Bottom View Of the Binary Tree (medium)
Solution: Bottom View Of the Binary Tree
Boundary of Binary Tree (medium)
Solution: Boundary of Binary Tree
Introduction to Comparison of Two Trees Pattern
Symmetric Tree (easy)
Solution: Symmetric Tree
Mirror Image Trees (medium)
Solution: Mirror Image Trees
Subtree of Another Tree (easy)
Solution: Subtree of Another Tree
Isomorphic Trees (medium)
Solution: Isomorphic Trees
Introduction to Serialize and Deserialize Tree Pattern
Serialize and Deserialize BST (medium)
Solution: Serialize and Deserialize BST
Verify Preorder Serialization of a Binary Tree (medium)
Solution: Verify Preorder Serialization of a Binary Tree
Create Binary Tree From Descriptions (medium)
Solution: Create Binary Tree From Descriptions
Serialize and Deserialize N-ary Tree (hard)
Solution: Serialize and Deserialize N-ary Tree
Solution: Maximum Width of Binary Tree

Problem Statement

Given the root of a binary tree, find the maximum width of the tree.

The maximum width is the widest level in the tree.

The width of a level is the number of nodes between the leftmost and rightmost non-null nodes, where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.

You can assume that the result will fit within a 32-bit signed integer.

Examples

Example 1

  • Input: root = [1, 2, 3, 4, null, null, 5]
Image
  • Output: 4
  • Justification: The maximum width is at the last level between nodes 4 and 5. It counts four positions: [4, null, null, 5].

Example 2

  • Input: root = [1, 2, 3, 4, null, 5, 6, null, 7]
Image
  • Output: 4
  • Justification: The maximum width is between nodes 4 and 6 at level 3, counting four positions: [4, null, 5, 6].

Example 3

  • Input: root = [1, 2, null, 3, 4, null, null, 5]
Image
  • Output: 2
  • Justification: The maximum width is at the third level, between nodes 3 and 4. It counts two positions: [3, 4].

Constraints:

  • The number of nodes in the tree is in the range [1, 3000].
  • -100 <= Node.val <= 100

Solution

To solve this problem, we will use a level order traversal approach, where we traverse the tree level by level from left to right. During traversal, we keep track of each node's position in a hypothetical "complete binary tree" to account for all gaps (nulls) between nodes at each level. We use a queue to store nodes along with their positions, which allows us to calculate the width of each level easily. At each level, we compare the positions of the leftmost and rightmost nodes to determine the width. The maximum width found across all levels is our answer.

This approach is effective because it leverages a breadth-first search (BFS) technique to explore each level fully before moving to the next, ensuring that we capture the correct width of every level. It is efficient in both time and space, given that it only requires storing nodes at one level at a time, making it well-suited for handling binary trees of reasonable size.

Step-by-Step Algorithm

  • Check if the tree is empty:

    • If the root is null, return 0 as the width.
  • Initialize a queue for level order traversal:

    • The queue will store pairs of nodes and their corresponding positions.
  • Add the root node to the queue with position 0.

  • Set a variable maxWidth to 0 to keep track of the maximum width found.

  • While the queue is not empty:

    • Get the number of nodes at the current level (size).

    • Get the minimum position index at this level (minIndex) to normalize positions.

    • Initialize two variables first and last to store the positions of the first and last nodes at this level.

    • For each node at the current level:

      • Dequeue the node and its position from the queue.
      • Normalize the position by subtracting minIndex from the currentIndex to avoid overflow issues.
      • Update first with the index value if it is the first node at this level.
      • Update last with the index value if it is the last node at this level.
      • Check if the left child exists:
        • Add the left child to the queue with position 2 * current_position.
      • Check if the right child exists:
        • Add the right child to the queue with position 2 * current_position + 1.
    • Calculate the width of the current level as last - first + 1.

    • Update maxWidth to the maximum of its current value and the width of the current level.

  • Return maxWidth after processing all levels.

Algorithm Walkthrough

Input: [1, 2, 3, 4, null, null, 5]

Given the binary tree:

    1
   / \
  2   3
 /     \
4       5

Initial Setup:

  • Queue: [(1, 0)] (Node 1 at position 0)
  • maxWidth: 0

Level 1

  • Size: 1 (Only the root node 1)
  • minIndex: 0 (Position of node 1)
  • Initialize first and last to 0.

Process Node 1:

  • Dequeue Node 1 with position 0.
  • Update first to 0 (first node at this level).
  • Update last to 0 (last node at this level).
  • Enqueue left child (2) with position 0.
  • Enqueue right child (3) with position 1.
  • Calculate Width: last - first + 1 = 0 - 0 + 1 = 1
  • Update maxWidth: max(0, 1) = 1.

Level 2

  • Size: 2 (Nodes 2 and 3)
  • minIndex: 0 (Position of node 2)
  • Initialize first and last to 0.

Process Node 2:

  • Dequeue Node 2 with position 0.
  • Update first to 0 (first node at this level).
  • Enqueue left child (4) with position 0 (no right child).

Process Node 3:

  • Dequeue Node 3 with position 1.
  • Update last to 1 (last node at this level).
  • Enqueue right child (5) with position 2*index + 1 = 2*1 + 1 = 3 (no left child).
  • Calculate Width: last - first + 1 = 1 - 0 + 1 = 2
  • Update maxWidth: max(1, 2) = 2.

Level 3

  • Size: 2 (Nodes 4 and 5)
  • minIndex: 0 (Position of node 4)
  • Initialize first and last to 0.

Process Node 4:

  • Dequeue Node 4 with position 0.
  • Update first to 0 (first node at this level).

Process Node 5:

  • Dequeue Node 5 with position 3.
  • Update last to 3 (last node at this level).
  • Calculate Width: last - first + 1 = 3 - 0 + 1 = 4
  • Update maxWidth: max(2, 4) = 4.

End

  • The queue is empty; all levels are processed.
  • Return maxWidth: 4.

Final Output: The maximum width of the binary tree is 4.

Code

Java
Saved to Cloud

. . . .

Complexity Analys

Time Complexity

  • The time complexity of this solution is , where N is the total number of nodes in the binary tree.
  • This is because we perform a level-order traversal (BFS) of the tree, visiting each node exactly once to determine the maximum width.

Space Complexity

  • The space complexity is , where W is the maximum width of the binary tree.
  • The space complexity is determined by the maximum number of nodes that could be stored in the queue at any given level of the tree. In the worst case, this will be the width of the widest level of the binary tree.
Maximum Width of Binary Tree (medium)
Maximum Level Sum of a Binary Tree (medium)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analys

Time Complexity

Space Complexity